package com.github.catvod.spider;

import android.content.Context;

import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.utils.Asset;
import com.github.catvod.utils.okhttp.OkHttpUtil;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 这个Spider 只是适配 takagen99-tvbox 客户端, FongMi-TV 不支持
 *
 * @Author zlliu
 * @Date 2025/7/14
 * @Description
 */
public class QQCartoon extends QQTv {
    private final static String joinStr = ",";

    private static JSONObject filterConfig;

    @Override
    public void init(Context context) throws Exception {
        try {
            //  动漫/电视剧筛选
            String json = Asset.read("qq-cartoon.json");
            filterConfig = new JSONObject(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String homeContent(boolean filter) {
        try {
            JSONObject result = new JSONObject();
            JSONArray classes = new JSONArray();
            // 把分类的id和名称取出来加到列表里
            classes.put(new JSONObject("{\"type_id\":\"cartoon\",\"type_name\":\"动漫\"}"));
            classes.put(new JSONObject("{\"type_id\":\"tv\",\"type_name\":\"电视剧\"}"));
            classes.put(new JSONObject("{\"type_id\":\"movie\",\"type_name\":\"电影\"}"));

            result.put("class", classes);
            //  查询电影分页数据
            String pageRequestUrl = "https://v.qq.com/x/bu/pagesheet/list?_all=1&append=1&channel=tv";
            String resultJson = OkHttpUtil.string(pageRequestUrl, getHeaders(null));
            if (filter) {
                result.put("filters", filterConfig);
            }
            try {
                Elements listItem = Jsoup.parse(resultJson).select(".list_item");
                JSONArray vodArray = new JSONArray();
                for (int i = 0; i < listItem.size(); i++) {
                    Element item = listItem.get(i);
                    String title = item.select("a").attr("title");
                    String pic = getPic(pageRequestUrl, item.select("img").attr("src"));
                    String remark = item.select(".figure_caption").text();
                    String id = item.select("a").attr("data-float");
                    JSONObject vodObject = new JSONObject();
                    vodObject.put("vod_id", id);
                    vodObject.put("vod_name", title);
                    vodObject.put("vod_pic", pic);
                    vodObject.put("vod_remarks", remark);
                    vodArray.put(vodObject);
                }
                result.put("list", vodArray);
            } catch (Exception e) {
                SpiderDebug.log(e);
            }
            return result.toString(4);
        } catch (Exception e2) {
            SpiderDebug.log(e2);
            return "";
        }
    }

    @Override
    public String categoryContent(String tid, String page, boolean filter, HashMap<String, String> extend) {
        try {
            StringBuilder url = new StringBuilder("https://v.qq.com/x/bu/pagesheet/list?_all=1&append=1&channel=" + tid + "&listpage=1&offset=" + ((Integer.parseInt(page) - 1) * 21) + "&pagesize=21");
            if (extend != null) {
                for (String str5 : extend.keySet()) {
                    String param = extend.get(str5).trim();
                    if (!param.isEmpty()) {
                        url.append("&").append(param);
                    }
                }
            }
            String content = OkHttpUtil.string(url.toString(), getHeaders(url.toString()));
            JSONObject result = new JSONObject();
            try {
                Elements listItems = Jsoup.parse(content).select(".list_item");
                JSONArray jSONArray = new JSONArray();
                String vodRemarks = "";
                for (int i = 0; i < listItems.size(); i++) {
                    Element item = listItems.get(i);
                    String vodName = item.select("a").attr("title");
                    String pic = getPic(url.toString(), item.select("img").attr("src"));
                    if (item.select(".figure_caption") != null) {
                        vodRemarks = item.select(".figure_caption").text();
                    }
                    String vodId = item.select("a").attr("data-float");
                    JSONObject vodObj = new JSONObject();
                    vodObj.put("vod_id", vodId);
                    vodObj.put("vod_name", vodName);
                    vodObj.put("vod_pic", pic);
                    vodObj.put("vod_remarks", vodRemarks);
                    jSONArray.put(vodObj);
                }
                result.put("page", page);
                result.put("pagecount", 300);
                result.put("limit", 21);
                result.put("total", 6300);
                result.put("list", jSONArray);
            } catch (Exception exception) {
                SpiderDebug.log(exception);
            }
            return result.toString(4);
        } catch (Exception e2) {
            SpiderDebug.log(e2);
            return "";
        }
    }

    @Override
    public String detailContent(List<String> list) {
        try {
            //  根据影片ID查询影片详细信息
            String url = "https://node.video.qq.com/x/api/float_vinfo2?cid=" + list.get(0);
            JSONObject response = new JSONObject(OkHttpUtil.string(url, getHeaders(url)));
            //  影片明细
            JSONObject vodObject = response.optJSONObject("c");
            if (vodObject == null) {
                return "";
            }
            JSONObject resultVodObject = new JSONObject();
            resultVodObject.put("vod_id", list.get(0));
            resultVodObject.put("vod_name", vodObject.optString("title"));
            resultVodObject.put("vod_pic", getPic(url, vodObject.optString("pic")));
            //  type_name类型为 String
//            resultVodObject.put("type_name", response.optJSONArray("typ").opt(0));
            resultVodObject.put("type_name", jsonArray2String(response.optJSONArray("typ"), "/"));
            resultVodObject.put("vod_year", vodObject.optString("year"));
            //  主演名称
            JSONArray optJSONArray = response.optJSONArray("nam").optJSONArray(0);
            resultVodObject.put("vod_actor", jsonArray2String(optJSONArray, joinStr));
            resultVodObject.put("vod_content", vodObject.optString("description"));
            JSONArray videoIdArray = vodObject.getJSONArray("video_ids");
            List<String> vodPlayUrlList = new ArrayList<>();
            // List 太长，要分组
            List<String> videoIdList = new Gson().fromJson(videoIdArray.toString(), new TypeToken<List<String>>(){}.getType());
            for (List<String> idList : Lists.partition(videoIdList, 15)) {
                String param = join(joinStr, idList);
                String url2 = "https://union.video.qq.com/fcgi-bin/data?otype=json&tid=682&appid=20001238&appkey=6c03bbe9658448a4&union_platform=1&idlist=" + param;
                String response2 = OkHttpUtil.string(url2, getHeaders(url2));
                JSONArray resultArray = new JSONObject(response2.substring(13, response2.length() - 1)).getJSONArray("results");
                for (int index = 0; index < resultArray.length(); index++) {
                    JSONObject fields = resultArray.getJSONObject(index).getJSONObject("fields");
                    if (!fields.optString("title").contains("预告")) {
                        StringBuilder vodPlayUrl = new StringBuilder();
                        String title = fields.optString("title");
                        String str = vodObject.optString("title") + "_";
                        vodPlayUrl.append(title.replace(str, ""));
                        vodPlayUrl.append("$https://v.qq.com/x/cover/");
                        vodPlayUrl.append(list.get(0));
                        vodPlayUrl.append("/");
                        vodPlayUrl.append(fields.optString("vid"));
                        vodPlayUrl.append(".html");
                        vodPlayUrlList.add(vodPlayUrl.toString());
                    }
                }
            }
            resultVodObject.put("vod_play_from", "qq");
            resultVodObject.put("vod_play_url", join("#", vodPlayUrlList));
            JSONObject result = new JSONObject();
            JSONArray vodArray = new JSONArray();
            vodArray.put(resultVodObject);
            result.put("list", vodArray);
            return result.toString(4);
        } catch (Exception e) {
            SpiderDebug.log(e);
            return "";
        }
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) {
        try {
            JSONObject result = new JSONObject();
            try {
                result.put("url", id);
                //  解析标识
                //  com.github.tvbox.osc.ui.fragment.PlayFragment.mObserverPlayResult.onChanged
                result.put("parse", 1);
//                result.put("jx", "1");

                //  配置parse前缀，可以匹配 com.github.tvbox.osc.bean.ParseBean的name
                //  com.fongmi.android.tv.player.ParseJob#setParse
                //  可以手动指定解析路径,如不指定，则会默认为超级解析
//                result.put("playUrl", "parse:聚合解析");
                return result.toString();
            } catch (Exception e) {
                SpiderDebug.log(e);
                return result.toString();
            }
        } catch (Exception e2) {
            SpiderDebug.log(e2);
            return "";
        }
    }

    private String jsonArray2String(JSONArray array, String joinStr) {
        List<String> arrayList = new ArrayList<>();
        for (int index = 0; index < array.length(); index++) {
            arrayList.add(array.optString(index));
        }
        return join(joinStr, arrayList);
    }

}
